import { handleActions } from 'redux-actions'
import util from '../util'

const init = {
	onboardingTemplate: {}
}

export default handleActions({
  'reset onboarding template': (state) => ({
    ...state,
    ...init
  }),
	'fetch onboarding template': (state, { payload }) => {
    return {
      ...state,
      onboardingTemplate: payload
    }
	},
  'delete onboarding document': (state, { payload }) => {
    return {
      ...state,
      onboardingTemplate: {
        ...state.onboardingTemplate,
        onboardingDocumentVOs: state.onboardingTemplate.onboardingDocumentVOs
        .filter(doc => doc.documentId != payload)
        .map((doc, i) => ({
          ...doc,
          logicalIndex: i
        }))
      }
    }
  },

  'add onboarding document': (state, { payload }) => ({
    ...state,
    onboardingTemplate: {
      ...state.onboardingTemplate,
      onboardingDocumentVOs: [
        ...state.onboardingTemplate.onboardingDocumentVOs,
        {
          ...payload,
          logicalIndex: state.onboardingTemplate.onboardingDocumentVOs.length
        }
      ]
    }
  }),
  'sort onboarding document': (state, { payload }) => {
    const { from, to } = payload
    const { onboardingDocumentVOs: list } = state.onboardingTemplate
    if (from < to) {
      return {
        ...state,
        onboardingTemplate: {
          ...state.onboardingTemplate,
          onboardingDocumentVOs: [
            ...list.slice(0, from),
            ...list[to],
            ...list.slice(from+1, to+1),
            list[from],
            ...list.slice(to+1)
          ].map((item, i) => ({
            ...item,
            logicalIndex: i
          }))
        }
      }
    } else {
      return {
        ...state,
        onboardingTemplate: {
          ...state.onboardingTemplate,
          onboardingDocumentVOs: [
            ...list.slice(0, to),
            list[from],
            ...list.slice(to, from),
            ...list.slice(from+1)
          ].map((item, i) => ({
            ...item,
            logicalIndex: i
          }))
        }
      }
    }
  }
}, init)
